class IterationsController < ApplicationController
  layout "application"

  def index
    list
    render :action => 'list'
  end

  def show_most_recent_iteration
    if Iteration.count == 0
      redirect_to :action => :list 
    else
      redirect_to :action => :show, :id => Iteration.most_recent_iteration.id
    end
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @iteration_pages, @iterations = paginate :iterations, 
      :order_by => 'iteration_number DESC', :per_page => 25
  end

  def show

    #TODO this could be simplified by always calling get_deliverables_for_resource
    #and have it handle the case when resource is nil.
    if params[:resource]
      resource = params[:resource]
      @iteration = Iteration.find(params[:id])
      @deliverables = @iteration.get_deliverables_for_resource resource
    else
      @iteration = Iteration.find(params[:id])
      @deliverables = @iteration.deliverables
    end

    @deliverables = Deliverable.sort_deliverables(@deliverables)
    @status = Iteration.get_completion_status(@deliverables)
  end

  
  def new
    deliverables = Iteration.most_recent_iteration.deliverables
    count = 0
    for deliverable in deliverables
     if deliverable.status == ''
       count = count + 1
     end 
    end

    if count > 0
       @warning = "Warning: Status of #{count} deliverables have not been set. "
       @warning << "It is recommended to set the status of all deliverables before creating a new iteration"
    end

    @iteration = Iteration.new
    @iteration.start_date = Date.today

    #Set end of iteration by default 2 weeks from today
    @iteration.end_date = @iteration.start_date + 14
    @iteration.iteration_number = Iteration.most_recent_iteration.iteration_number + 1
  end

  def create
    @iteration = Iteration.new(params[:iteration])
    @iteration.add_deliverables_from_most_recent_iteration

    if @iteration.save
      flash[:notice] = 'Iteration was successfully created.'
      show_most_recent_iteration
    else
      render :action => 'new'
    end
  end

  def edit
    @iteration = Iteration.find(params[:id])
  end

  def update
    @iteration = Iteration.find(params[:id])
    if @iteration.update_attributes(params[:iteration])
      flash[:notice] = 'Iteration was successfully updated.'
      redirect_to :action => 'show', :id => @iteration
    else
      render :action => 'edit'
    end
  end

  def destroy
    Iteration.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
